package com.link.play.fit.ai.utils

import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task
import com.google.firebase.messaging.FirebaseMessaging
import com.link.play.fit.ai.kv.AuthCache
import org.json.JSONObject

object FirebaseUtils {

    fun initFirebase() {
        //FirebaseApp.initializeApp(context)
        getToken()
    }

//    fun subscribeToTopic(topic: String) {
//        FirebaseMessaging.getInstance().subscribeToTopic(topic)
//            .addOnCompleteListener { task ->
//                if (task.isSuccessful) {
//                    EventUtils.event("FCM_Topic_${topic}")
//                }
//            }
//    }

//    fun unsubscribeFromTopic(topic: String) {
//        FirebaseMessaging.getInstance().unsubscribeFromTopic(topic)
//            .addOnCompleteListener { task ->
//                if (task.isSuccessful) {
//
//                } else {
//
//                }
//            }
//    }

    private fun getToken() {
        FirebaseMessaging.getInstance().token
            .addOnCompleteListener(object : OnCompleteListener<String> {
                override fun onComplete(task: Task<String>) {
                    if (!task.isSuccessful) {
                        LogX.d("FCM", "Fetching FCM registration token failed", task.exception)
                        return
                    }
                    // Get new FCM registration token
                    val token: String = task.result
                    eventToken(token)
                    // Handle new token
                    LogX.d("FCM", "FCM Registration Token: $token")
                }
            })
    }

    private fun eventToken(token: String) {
        if (AuthCache.tokenCount < 3 || token != AuthCache.fcmToken) {
            val json = JSONObject()
            json.put("token", token)
            EventUtils.event("fcm_message_received", ext = json) {
                AuthCache.tokenCount++
            }
            AuthCache.fcmToken = token
        }
    }
}